//
// Created by ct on 2020/12/2.
//

#include "peer_log_parser.h"

namespace peer_log_parser {

    log_parser::log_parser(std::string filepath,
                           std::string date_str = "ALL",
                           std::uint16_t max = 100,
                           std::string index_str = "ERRO")
            : file_path(std::move(filepath)),
              in(file_path),
              date_str(std::move(date_str)),
              max_line(max),
              index(std::move(index_str)) {
        result_queue = std::make_shared<std::queue<std::string> >();
    }

    std::string & log_parser::replace_all_distinct(std::string &str, const std::string &old_value,
                                                   const std::string &new_value) {
        for (std::string::size_type pos(0); pos != std::string::npos; pos += new_value.length()) {
            if ((pos = str.find(old_value, pos)) != std::string::npos) {
                str.replace(pos, old_value.length(), new_value);
            } else { break; }
        }
        return str;
    }

    std::string log_parser::queue_to_json() {
        std::string res = "[";
        for (; !result_queue->empty();) {
            res.append("\"");
            res.append(replace_all_distinct(result_queue->front(),"\"","\\\""));
            result_queue->pop();
            if (result_queue->empty()){
                res.append("\"");
                break;
            }
            res.append("\",");
        }
        res.append("]");
        return res;
    }

    std::string log_parser::result() {
        std::string line_str;
        if (date_str == "ALL") {
            date_str = "";
        }
        while (getline(in, line_str)) {
            if (line_str.find(index) != std::string::npos &&
                line_str.find(date_str) != std::string::npos) {
                //  std::cout<<"---"<<std::endl;
                if (result_queue->size() < max_line) {
                    result_queue->push(line_str);
                } else {
                    result_queue->pop();
                    result_queue->push(line_str);
                }
            }
        }
        return queue_to_json();
    }
} // namespace peer_log_parser